/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package lbim.server.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.Vector;
import lbim.server.main.LocateIMServer;
import lbim.server.model.Message;

/**
 *
 * @author Jestan
 */
public class MessageStore {
    private static HashMap<String,Vector> storage = new HashMap<String, Vector>();

    public static void createInbox(String sessionId) {
        storage.put(sessionId, new Vector<Message>());
    }

    public static boolean  putMessage(String sessionId, Message message) {
        if(storage.containsKey(sessionId)) {
            storage.get(sessionId).add(message);
            return true;
        } else {
            return false;
        }
    }

    public static void putPresenceUpdateMessage(String sessionId, Message message) {
        ArrayList<String> friendsSessionIds = getFriendsSessionIds(sessionId);
        for(String sid: friendsSessionIds ) {
            if(storage.containsKey(sid))
            storage.get(sid).add(message);
        }
    }

    public static Message getMessage(String sessionId) {
        if(storage.containsKey(sessionId) && !storage.get(sessionId).isEmpty()) {
            return (Message) storage.get(sessionId).remove(0);
        } else {
            throw  new NoSuchElementException("session does not exist");
        }
    }

    public static boolean  isAck(String sessionId) {
        if (storage.containsKey(sessionId)) {
            return !storage.get(sessionId).isEmpty();
        } else {
            return false;
        }
    }

    private static ArrayList<String> getFriendsSessionIds(String sid) {
        ArrayList<String> friendsSessionIds = new ArrayList<String>();
        Set<String> cSet = LocateIMServer.currentSessions.keySet();
        for (String currentSid : cSet) {
            if (!sid.equals(currentSid)) {
                friendsSessionIds.add(currentSid);
            }
        }

        return friendsSessionIds;
    }

}
